<!--
  Copyright 2019 Hackware SpA <human@hackware.cl>
  This file is part of "Hackware Userland" and licensed under the terms
  of the GNU Affero General Public License version 3, or (at your option)
  a later version. You should have received a copy of this license along
  with the software. If not, see <https://www.gnu.org/licenses/>.
-->

<template>
  <form
    class="login-by-password"
    @submit.prevent="submitLogin"
  >
    <h1>Accede a tu panel</h1>
    <div
      v-if="errorMessage"
      class="login-error"
    >
      <i class="fa fa-exclamation-triangle" />
      {{ errorMessage }}
    </div>
    <input
      :value="this.$route.query.username"
      id="username"
      type="text"
      placeholder="Usuario o email"
      name="username"
      required
      autofocus
    >
    <input
      :value="this.$route.query.password"
      id="password"
      type="password"
      placeholder="Contraseña"
      name="password"
      required
    >
    <div class="checkbox-container">
      <input
        id="remember"
        type="checkbox"
        name="remember"
      >
      <label for="remember">Recordarme</label>
    </div>
    <button
      id="btnLogin"
      type="submit"
    >
      Iniciar sesión
      <i class="fa fa-sign-in-alt" />
    </button>
    <p>
      ¿Sin contraseña?
      <router-link :to="{ name: 'login-by-email' }">
        solicita acceso inmediato aquí
      </router-link>
    </p>
  </form>
</template>

<script>
export default {
  name: 'LoginByPassword',
  data() {
    return {
      errorMessage: null,
    };
  },
  methods: {
    submitLogin(event) {
      const btnLogin = document.getElementById('btnLogin');

      btnLogin.setAttribute('disabled', true);
      this.errorMessage = null;

      return this.$fetcher.hawesePost('/auth/login', event.target, {}, false)
        .then(response => response.json())
        .then((body) => {
          if ('error' in body) {
            btnLogin.removeAttribute('disabled');
            this.errorMessage = body.error.message;
          } else {
            this.$auth.setUser(body);
            this.$router.push('/');
            this.$emit('login');
          }
        });
    },
  },
};
</script>
